package Leetcode100Hot;

import org.junit.Test;

import java.util.*;

/*
合并 K 个升序链表
给你一个链表数组，每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中，返回合并后的链表。

示例 1：
输入：lists = [[1,4,5],[1,3,4],[2,6]]
输出：[1,1,2,3,4,4,5,6]
解释：链表数组如下：
[
  1->4->5,
  1->3->4,
  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2：
输入：lists = []
输出：[]
示例 3：
输入：lists = [[]]
输出：[]

提示：
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
 */
public class _63合并K个升序链表 {

    @Test
    public void test() {
        ListNode listNode1 = new ListNode(1);
        listNode1.next = new ListNode(4);
        listNode1.next.next = new ListNode(5);
        ListNode listNode2 = new ListNode(1);
        listNode2.next = new ListNode(3);
        listNode2.next.next = new ListNode(4);
        ListNode listNode3 = new ListNode(2);
        listNode3.next = new ListNode(6);
        ListNode[] listNodes = {listNode1, listNode2, listNode3};
        ListNode listNode = mergeKLists(listNodes);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //合并升序链表 * k
    //AC  1500ms
    //优化： 纵向合并要用map进行记录，还要进行多个循环嵌套，效率不行，可以考虑横向合并。
    //合并两个升序链表==> 可以通过两个链表得到一个有序的升序链表
    //因此将思路迁移， 合并k个升序链表 = 多次使用 合并两个升序链表 即横向合并， 这样代码耦合度高，效率快
    public ListNode mergeKLists(ListNode[] lists) {
        Map<Integer, ListNode> map = new HashMap<>();
        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                map.put(i, lists[i]);
            }
        }
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        Set<Map.Entry<Integer, ListNode>> entries = map.entrySet();
        while (entries.size() > 1){
            int minIndex = entries.iterator().next().getKey();
            for (Map.Entry<Integer, ListNode> entry : entries) {
                ListNode node = entry.getValue();
                int val = node.val;
                minIndex = Math.min(map.get(minIndex).val, val) == val ? entry.getKey() : minIndex;
            }
            ListNode next = map.get(minIndex);
            cur.next = next;
            cur = cur.next;
            next = next.next;
            if (next != null){
                map.put(minIndex, next);
            }else {
                map.remove(minIndex);
            }
        }
        Collection<ListNode> values = map.values();
        for (ListNode value : values) {
            cur.next = value;
        }
        return dummy.next;
    }

    //官解：方法一：顺序合并
    //O(kn^2)
    //100ms
    //ps: 我的题解思路是纵向合并，由于加入了map效率太低
    /*
    作者：力扣官方题解
    链接：https://leetcode.cn/problems/merge-k-sorted-lists/solutions/219756/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/
     */
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            ListNode ans = null;
            for (int i = 0; i < lists.length; ++i) {
                ans = mergeTwoLists(ans, lists[i]);
            }
            return ans;
        }

        public ListNode mergeTwoLists(ListNode a, ListNode b) {
            if (a == null || b == null) {
                return a != null ? a : b;
            }
            ListNode head = new ListNode(0);
            ListNode tail = head, aPtr = a, bPtr = b;
            while (aPtr != null && bPtr != null) {
                if (aPtr.val < bPtr.val) {
                    tail.next = aPtr;
                    aPtr = aPtr.next;
                } else {
                    tail.next = bPtr;
                    bPtr = bPtr.next;
                }
                tail = tail.next;
            }
            tail.next = (aPtr != null ? aPtr : bPtr);
            return head.next;
        }
    }

    //官解：方法二：分治合并
    //O(kn×logk)    1ms
    //ps: 大问题化解为小问题，要有宏观视角
    //ps: 官解有图
    /*
    作者：力扣官方题解
    链接：https://leetcode.cn/problems/merge-k-sorted-lists/solutions/219756/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/
     */
    class Solution2 {
        public ListNode mergeKLists(ListNode[] lists) {
            return merge(lists, 0, lists.length - 1);
        }

        public ListNode merge(ListNode[] lists, int l, int r) {
            if (l == r) {
                return lists[l];
            }
            if (l > r) {
                return null;
            }
            int mid = (l + r) >> 1;
            return mergeTwoLists(merge(lists, l, mid), merge(lists, mid + 1, r));
        }

        public ListNode mergeTwoLists(ListNode a, ListNode b) {
            if (a == null || b == null) {
                return a != null ? a : b;
            }
            ListNode head = new ListNode(0);
            ListNode tail = head, aPtr = a, bPtr = b;
            while (aPtr != null && bPtr != null) {
                if (aPtr.val < bPtr.val) {
                    tail.next = aPtr;
                    aPtr = aPtr.next;
                } else {
                    tail.next = bPtr;
                    bPtr = bPtr.next;
                }
                tail = tail.next;
            }
            tail.next = (aPtr != null ? aPtr : bPtr);
            return head.next;
        }
    }

    //官解；方法三：使用优先队列合并
    //O(kn×logk)  5ms
    //PriorityQueue
    /*
    作者：力扣官方题解
    链接：https://leetcode.cn/problems/merge-k-sorted-lists/solutions/219756/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/
     */
    class Solution3 {
        class Status implements Comparable<Status> {
            int val;
            ListNode ptr;

            Status(int val, ListNode ptr) {
                this.val = val;
                this.ptr = ptr;
            }

            public int compareTo(Status status2) {
                return this.val - status2.val;
            }
        }

        PriorityQueue<Status> queue = new PriorityQueue<Status>();

        public ListNode mergeKLists(ListNode[] lists) {
            for (ListNode node: lists) {
                if (node != null) {
                    queue.offer(new Status(node.val, node));
                }
            }
            ListNode head = new ListNode(0);
            ListNode tail = head;
            while (!queue.isEmpty()) {
                Status f = queue.poll();
                tail.next = f.ptr;
                tail = tail.next;
                if (f.ptr.next != null) {
                    queue.offer(new Status(f.ptr.next.val, f.ptr.next));
                }
            }
            return head.next;
        }
    }

}
